<template>
  <div class="app-container">
    <el-form
      :model="formData"
      ref="formData"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="项目名称" prop="voiceType">
        <el-select
          v-model="formData.projectId"
          filterable
          placeholder="请选择"
          clearable
          @change="onChangeProduct"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="chatText">
        <el-input
          v-model="formData.taskName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="onClickAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="multiple"
          size="mini"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格   -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="执行项目" align="center" prop="projectName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="进度"
        align="center"
        prop="callCustomerNumber"
        :formatter="
          ({ callCustomerNumber, totalCustomerNumber }) => {
            return `${callCustomerNumber || 0}/${totalCustomerNumber || 0}`;
          }
        "
      ></el-table-column>
      <el-table-column
        label="Ai机器人"
        align="center"
        prop="pitchRatio"
      ></el-table-column>
      <el-table-column
        label="执行状态"
        align="center"
        prop="status"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" @click="onImport(scope.row)" type="text"
            >导入</el-button
          >
          <el-button size="mini" @click="onQuickImport(scope.row)" type="text"
            >快速导入</el-button
          >
          <el-button size="mini" @click="onClearUncalled(scope.row)" type="text"
            >清理未呼数据</el-button
          >
          <el-button
            size="mini"
            @click="onRecoverUncalled(scope.row)"
            type="text"
            >回收未呼数据</el-button
          >
          <el-button size="mini" @click="handleUpdate(scope.row)" type="text"
            >定时器</el-button
          >
          <el-button size="mini" @click="onTimeline(scope.row)" type="text"
            >时间线</el-button
          >
          <el-button size="mini" @click="onMonitoring(scope.row)" type="text"
            >实时监控</el-button
          >
          <el-button size="mini" @click="onStatus(scope.row)" type="text">{{
            scope.row.status === "正在执行"
              ? "停止"
              : scope.row.status === "已停止"
              ? "执行"
              : ""
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pagination.pageNum"
      :limit.sync="pagination.pageSize"
      @pagination="getList"
    />

    <add-task-dialog
      :add-task-dialog-show="addTaskDialogShow"
      @onCloseAddTaskDialog="onCloseAddTaskDialog"
    ></add-task-dialog>

    <import-data-dialog
      v-if="importShow"
      :importShow="importShow"
      :taskId="taskId"
      :uploadUrl="'/system/task/importCustomer'"
      :downloadUrl="'system/task/importTemplate'"
      @onImportCancel="onImportCancel"
    ></import-data-dialog>

    <quick-import-dialog
      :quickImportShow="quickImportShow"
      :taskId="taskId"
      @onCloseQuickImport="onCloseQuickImport"
    ></quick-import-dialog>

    <recoverDataDialog
      :recoverDataDialogShow="recoverDataDialogShow"
      :taskId="taskId"
      @onCloseRecoverDataDialog="onCloseRecoverDataDialog"
    ></recoverDataDialog>

    <timelineDialog
      :timelineDialogShow="timelineDialogShow"
      :taskId="taskId"
      @onCloseTimelineDialog="onCloseTimelineDialog"
    ></timelineDialog>

    <!-- <realMonitoringDialog
      :realMonitoringDialogShow="realMonitoringDialogShow"
      :taskId="taskId"
    ></realMonitoringDialog> -->

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog title="定时器" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择任务分组">
                <el-option
                  v-for="dict in dict.type.sys_job_group"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="invokeTarget">
              <span slot="label">
                调用方法
                <el-tooltip placement="top">
                  <div slot="content">
                    Bean调用示例：ryTask.ryParams('ry')
                    <br />Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                    <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input
                v-model="form.invokeTarget"
                placeholder="请输入调用目标字符串"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input
                v-model="form.cronExpression"
                placeholder="请输入cron执行表达式"
              >
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.jobId !== undefined">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_job_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy" size="small">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent" size="small">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="Cron表达式生成器"
      :visible.sync="openCron"
      append-to-body
      destroy-on-close
      class="scrollbar"
    >
      <crontab
        @hide="openCron = false"
        @fill="crontabFill"
        :expression="expression"
      ></crontab>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskList,
  deleteTask,
  removeCustomer,
  groupCall,
  createTask,
} from "@/api/taskManagement/taskList.js";
import { projectList } from "@/api/projectManagement/list";
import { getList } from "@/api/customerService/tts-test-list";
import { listData } from "@/api/system/dict/data";
import addTaskDialog from "./components/addTaskDialog.vue";
import importDataDialog from "./components/importDataDialog.vue";
import quickImportDialog from "./components/quickImportDialog.vue";
import recoverDataDialog from "./components/recoverDataDialog.vue";
import timelineDialog from "./components/timelineDialog.vue";
import { updateJob } from "@/api/monitor/job";
import Crontab from "@/components/Crontab";
export default {
  name: "taskList",
  components: {
    addTaskDialog,
    importDataDialog,
    quickImportDialog,
    Crontab,
    recoverDataDialog,
    timelineDialog,
  },
  dicts: ["sys_job_group", "sys_job_status"],
  data() {
    return {
      loading: false,
      tableData: [], //表格数据
      showSearch: true, //显示搜索条件
      // 查询参数
      formData: {
        projectId: "",
        taskName: "",
      },
      productList: [],
      voiceTypeList: [], //音色数据
      pagination: {
        pageNum: 1,
        pageSize: 10,
      },
      dateRange: [], //日期范围
      total: 0,
      importShow: false, //导入
      quickImportShow: false, //导入
      addDialogShow: false,
      voiceTypeList: [],
      addTaskDialogShow: false,
      recoverDataDialogShow: false,
      timelineDialogShow: false,
      realMonitoringDialogShow: false,
      // 表单参数
      form: {},
      open: false,
      openCron: false,
      // 传入的表达式
      expression: "",
      taskId: "",
      ids: [],
      multiple: true,
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        invokeTarget: [
          {
            required: true,
            message: "调用目标字符串不能为空",
            trigger: "blur",
          },
        ],
        cronExpression: [
          {
            required: true,
            message: "cron执行表达式不能为空",
            trigger: "blur",
          },
        ],
        currentRow: null,
      },
    };
  },

  async created() {
    await this.getProductList();
    await this.getList();
  },
  methods: {
    async getListType() {
      const { rows } = await listData({
        pageNum: 1,
        pageSize: 1000,
        dictType: "sys_voice_type",
      });
      this.voiceTypeList = rows || [];
    },

    // 项目列表
    async getProductList() {
      const params = {
        status: "",
        projectName: "",
        pageNum: 1,
        pageSize: 1000,
      };
      const { code, rows } = await projectList(params);
      if (code === 200) {
        this.productList = rows;
      }
    },

    // 任务列表
    async getList() {
      const params = {
        ...this.formData,
        ...this.pagination,
      };
      const { code, rows } = await taskList(params);
      if (code === 200) {
        this.tableData = rows;
      }
    },

    onChangeProduct(event) {
      this.projectId = event;
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.jobId != undefined) {
            updateJob(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJob(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.currentRow = row;
      this.open = true;
      this.form.jobName = row.taskName;
      this.form.invokeTarget = `com.ruoyi.web.controller.system.SsscAichangeController.groupCall(${row.projectId}_${row.id})`;
      // getJob(jobId).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改任务";
      // });
    },

    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cronExpression;
      this.openCron = true;
    },

    // 表单重置
    reset() {
      this.form = {
        projectId: "",
        taskName: "",
      };
      this.resetForm("form");
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cronExpression = value;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.pagination.pageNum = 1;
      this.getList();
    },

    // 删除
    handleDelete() {
      const roleIds = this.ids;
      this.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return deleteTask(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.formData = {
        projectId: "",
        taskName: "",
      };
      this.dateRange = [];
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      const url = `system/sysTtsVoice/exportTtsVoice`;
      const voiceAll = this.voiceTypeList.find(
        (el) => el.dictValue == this.formData.voiceType
      );
      const formData = JSON.parse(JSON.stringify(this.formData));
      delete formData["voiceType"];
      let data = {
        ...formData,
        voiceName: voiceAll?.dictLabel || undefined, //音色
        ...this.pagination,
      };
      if (this.dateRange?.length) {
        data.params =
          typeof data.params === "object" &&
          data.params !== null &&
          !Array.isArray(data.params)
            ? data.params
            : {};
        data.params["beginTime"] = this.dateRange[0];
        data.params["endTime"] = this.dateRange[1];
      }
      this.download(
        url,
        {
          ...data,
        },
        `ttsTestList_${new Date().getTime()}.xlsx`
      );
    },

    // 导入
    onImport(row) {
      this.taskId = String(row.id);
      this.importShow = true;
    },

    onImportCancel() {
      this.taskId = "";
      this.getList();
      this.importShow = false;
    },

    // 快速导入
    onQuickImport(row) {
      this.taskId = String(row.id);
      this.quickImportShow = true;
    },

    onCloseQuickImport() {
      this.taskId = "";
      this.getList();
      this.quickImportShow = false;
    },

    // 清除未呼数据
    async onClearUncalled(row) {
      this.$confirm("确定要删除这个任务中的未呼数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { id = "" } = row;
          const { code, msg } = await removeCustomer(id);
          this.$message({
            type: "success",
            message: msg,
          });
          this.getList();
        })
        .catch(() => {
          console.log("取消");
        });
    },

    // 回收未呼数据
    onRecoverUncalled(row) {
      this.taskId = String(row.id) || "";
      this.recoverDataDialogShow = true;
    },

    onCloseRecoverDataDialog() {
      this.taskId = "";
      this.recoverDataDialogShow = false;
      this.getList();
    },

    // 定时器
    onTimer() {},

    // 时间线
    onTimeline(row) {
      this.taskId = String(row.id) || "";
      this.timelineDialogShow = true;
    },

    onCloseTimelineDialog() {
      this.taskId = "";
      this.timelineDialogShow = false;
    },

    // 实时监控
    onMonitoring({ projectId = 0 }) {
      this.$router.push(
        "/taskManagement/taskList-realMonitoring/index/" + projectId
      );
    },

    // 音频下载
    async onAudioDownload(row) {
      console.log(row, "row");
      const fileUrl = row?.ttsUrl;
      // 打开新标签页进行下载
      window.open(fileUrl, "_blank");
    },

    async toStop(projectId, id) {
      const params = {
        planId: `${projectId}_${id}`,
      };
      const { code, msg } = await groupCall(params);
      if (code === 200) {
        this.$message.success(msg);
        this.getList();
      }
    },

    onStatus({ status, projectId, id }) {
      if (status === "已停止") {
        this.toStop(projectId, id);
      }
      if (status === "正在执行") {
        this.onPending(id);
      }
    },

    async onPending(id) {
      const params = {
        id,
        status: "已停止",
      };
      const { code, msg } = await createTask(params);
      if (code === 200) {
        this.$message.success(msg);
        this.getList();
      }
    },

    // 新建
    onClickAdd() {
      this.addTaskDialogShow = true;
    },

    onCloseAddTaskDialog() {
      this.addTaskDialogShow = false;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    // 取消
    onClose() {
      this.addDialogShow = false;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped></style>
